const db = require('../db/db')
const { paging } = require('../utils/paging')
const {host} = require('../config/config')
module.exports = {
    // 获取所有博客
    getBlogs: async (ctx, next) => {
        // 1.获取客户端传来的信息
        const msg = ctx.request.body
        const pageObj = await paging(ctx)
        const startPage = pageObj.startPage
        const endPage = pageObj.endPage
        // 5.判断用户是谁 root就是可以获取所有用户的博客，其他的就只能获取自己的博客
        // 5-1.如果日期范围为null
        if (msg.author == 'root' && (msg.date == null || msg.date == '')) {
            await db.promise().query('select * from blogs where isdel=0').then(async results => {
                const [resultss] = results
                const total = resultss.length
                await db.promise().query('select * from blogs where isdel=0  limit ?,? ', [startPage, endPage]).then(res => {
                    const [blogs] = res
                    ctx.body = {
                        code: 1000,
                        msg: '获取成功',
                        total: total,
                        blogs: blogs,

                    }
                }).catch(err => {
                    ctx.body = {
                        code: 1001,
                        msg: '获取失败' + err
                    }
                })
            })
            // console.log(1);
            // 5-1.如果日期范围不为null
        } else if (msg.author == 'root' && (msg.date !== null || msg.date !== '')) {
            await db.promise().query('select * from blogs where isdel=0 and create_time between ? and ?', [msg.date[0], msg.date[1]]).then(async results => {
                const [resultss] = results
                const total = resultss.length
                await db.promise().query('select * from blogs where isdel=0 and create_time between ? and ? limit ?,?', [msg.date[0], msg.date[1], startPage, endPage]).then(res => {
                    const [blogs] = res
                    ctx.body = {
                        code: 1000,
                        msg: '获取成功',
                        total: total,
                        blogs: blogs,

                    }
                }).catch(err => {
                    ctx.body = {
                        code: 1001,
                        msg: '获取失败' + err
                    }
                })
            })
            // console.log(2);
            // 5-3.普通用户传了日期范围
        } else if (msg.date !== null && msg.date !== '') {
            await db.promise().query('select * from blogs where isdel=0 and author=? and create_time between ? and ?', [msg.author, msg.date[0], msg.date[1]]).then(async results => {
                const [resultss] = results
                const total = resultss.length
                await db.promise().query('select * from blogs where isdel=0 and author=? and create_time between ? and ? limit ?,?', [msg.author, msg.date[0], msg.date[1], startPage, endPage]).then(res => {
                    const [blogs] = res
                    ctx.body = {
                        code: 1000,
                        msg: '获取成功',
                        total: total,
                        blogs: blogs,

                    }
                }).catch(err => {
                    ctx.body = {
                        code: 1001,
                        msg: '获取失败' + err
                    }
                })
            })
            // console.log(3);
            // 5-4.普通用户没传日期范围
        } else {
            await db.promise().query('select * from blogs where isdel=0 and author=?', [msg.author]).then(async results => {
                const [resultss] = results
                const total = resultss.length
                await db.promise().query('select * from blogs where isdel=0 and author=? limit ?,?', [msg.author, startPage, endPage]).then(res => {
                    const [blogs] = res
                    ctx.body = {
                        code: 1000,
                        msg: '获取成功',
                        total: total,
                        blogs: blogs,

                    }
                }).catch(err => {
                    ctx.body = {
                        code: 1001,
                        msg: '获取失败' + err
                    }
                })
            })
            // console.log(4);
        }

    },
    // 删除博客（批量恢复）
    delBlog: async (ctx, next) => {
        const { blogId, isdel } = ctx.request.body
        if (blogId) {
            let isdell = isdel == 0 ? 1 : 0
            const date = new Date()
            await db.promise().query('update blogs set isdel=?,change_time=? where id=?', [isdell, date, blogId]).then(res => {
                if (isdel == 0) {
                    ctx.body = {
                        code: 200,
                        msg: '删除成功'
                    }
                } else {
                    ctx.body = {
                        code: 200,
                        msg: '恢复成功'
                    }
                }
            }).catch(err => {
                if (isdel == 0) {
                    ctx.body = {
                        code: 200,
                        msg: '删除失败' + err
                    }
                } else {
                    ctx.body = {
                        code: 200,
                        msg: '恢复失败' + err
                    }
                }

            })
        } else {
            const blogedArr = ctx.request.body
            blogedArr.forEach(async item => {
                let isdell = item.isdel == 0 ? 1 : 0
                await db.promise().query('update blogs set isdel=? where id=?', [isdell, item.id]).then(res => {
                    return true
                }).catch(err => {
                    ctx.body = {
                        code: 201,
                        msg: '批量恢复失败' + err
                    }
                })
            });
            ctx.body = {
                code: 200,
                msg: '批量恢复成功'
            }
        }
    },
    // 获取被删博客
    getbloged: async (ctx, next) => {
        // 分页
        const pageObj = await paging(ctx)
        const startPage = pageObj.startPage
        const endPage = pageObj.endPage
        const [totalRes] = await db.promise().query('select * from blogs where isdel=1')
        const total = totalRes.length
        await db.promise().query('select * from blogs where isdel=1 order by create_time desc limit ?,?', [startPage, endPage]).then(res => {
            ctx.body = {
                code: 1000,
                msg: '获取成功',
                blogeds: res[0],
                total: total,
            }

        }).catch(err => {
            ctx.body = {
                code: 1001,
                msg: '获取失败' + err
            }
        })
    },
    // 永久删除(批量)
    delbloged: async (ctx, next) => {
        const { blogId } = ctx.request.body
        if (blogId) {
            console.log(ctx.request.body);
            await db.promise().query('delete from blogs where id=?', [blogId]).then(res => {
                ctx.body = {
                    code: 200,
                    msg: '删除成功'
                }
            }).catch(err => {
                ctx.body = {
                    code: 201,
                    msg: '删除失败' + err
                }
            })
        } else {
            const blogedArr = ctx.request.body
            blogedArr.forEach(async item => {
                await db.promise().query('delete from blogs where id=?', [item.id]).then(res => {
                    return true
                }).catch(err => {
                    ctx.body = {
                        code: 201,
                        msg: '删除失败' + err
                    }
                })
            });
            ctx.body = {
                code: 200,
                msg: '删除成功'
            }
        }
    },
    // 获取展示的博客
    getDisplayBlogs:async (ctx,next)=>{
        const pageObj = await paging(ctx)
        const startPage = pageObj.startPage
        const endPage = pageObj.endPage
        await db.promise().query('select * from blogs where isdel=0').then(async results => {
            const [resultss] = results
            const total = resultss.length
            await db.promise().query('select * from blogs where isdel=0 and categorize!=? order by create_time desc limit ?,?', ['帖子',startPage, endPage]).then(res => {
                const [blogs] = res
                ctx.body = {
                    code: 1000,
                    msg: '获取成功',
                    total: total,
                    blogs: blogs,

                }
            }).catch(err => {
                ctx.body = {
                    code: 1001,
                    msg: '获取失败' + err
                }
            })
        })
    },
    // 发布博客
    publicBlog:async (ctx,next)=>{
       const  {title,introduction,categorize,author,content} =  ctx.request.body
       if(author == ''){
        ctx.body = {
            code:202,
            msg:"请先登录"
        }
       }
       const create_time = new Date()
       let blogface =''
       if(ctx.request.body.blogface==''){
        blogface = host + '/blogFace/%E6%96%B0%E5%B9%B4%E5%BF%AB%E4%B9%90.jpg'
       }else{
        blogface = ctx.request.body.blogface
       }
       await db.promise().query('insert into blogs (title,introduction,categorize,author,content,create_time,blogface) values (?,?,?,?,?,?,?)',[title,introduction,categorize,author,content,create_time,blogface]).then(res=>{
        ctx.body = {
            code:200,
            msg:"发布成功"
        }
       })
    },
    // 模糊查询
    queryBlog:async(ctx,next)=>{
        let keyword = ctx.request.body;
        await db.promise().query(`select * from blogs where title like "%${keyword.keyword}%"`,).then(res=>{
            ctx.body = {
                code:200,
                msg:'搜索成功',
                blogs:res[0]
            }
        }).catch(err=>{
            ctx.body = {
                code:201,
                msg:'搜索失败'+err,
            }

        })
    },
    // 获取单个展示博客
    displayBlog: async(ctx,next)=>{
        let {id} = ctx.request.body
        await db.promise().query('select * from blogs where id=?',[id]).then(res=>{
            ctx.body = {
                code:1000,
                msg:'获取成功',
                blog:res[0][0]
            }
        }).catch(err=>{
            ctx.body = {
                code:1001,
                msg:'获取失败'+err,
            }

        })
    },
    // 帖子管理
    getForum:async (ctx,next)=>{
        const pageObj = await paging(ctx)
        const startPage = pageObj.startPage
        const endPage = pageObj.endPage
        await db.promise().query('select * from blogs where isdel=0').then(async results => {
            const [resultss] = results
            const total = resultss.length
            await db.promise().query('select * from blogs where isdel=0 and categorize=? order by create_time desc limit ?,?', ['帖子',startPage, endPage]).then(res => {
                const [forum] = res
                ctx.body = {
                    code: 1000,
                    msg: '获取成功',
                    total: total,
                    forum: forum,

                }
            }).catch(err => {
                ctx.body = {
                    code: 1001,
                    msg: '获取失败' + err
                }
            })
        })
    },
    goGood:async (ctx,next)=>{
       const {blog_id} = ctx.request.body
        const [res] = await db.promise().query('select good from blogs where id=?',blog_id)
        let num = res[0].good
        let goodNum = num + 1
        await db.promise().query('update blogs set good=? where id=?',[goodNum,blog_id]).then(res=>{
           if(res.length > 0){
            ctx.body = {
                code:200,
                msg:'点赞成功'
            }
           }
        })
    }
}
